package model;

import helperclasses.DbUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.sql.DataSource;

public class ProductsName {
	private String[] productsNames;
	private String desfasurat;

	public String getDesfasurat() {
		return desfasurat;
	}

	public void setDesfasurat(String desfasurat) {
		this.desfasurat = desfasurat;
	}

	public ProductsName() {
		try {
			ArrayList<String> names = new ArrayList<String>();
			names = getNames();
			//setProductsNames(ConvertToArray(names));
			setDesfasurat(ConvertToDesfasurat(names));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String ConvertToDesfasurat(ArrayList<String> pnList) {
		String gr;
		gr = "[";
		for (int i = 0; i < pnList.size(); i++) {
			gr += "\"";
			gr += pnList.get(i);
			gr += "\"";
			if (i < pnList.size() - 1) {
				gr += ", ";
			} else {
				gr += "]";
			}
		}
		return gr;
	}

//	private String[] ConvertToArray(ArrayList<String> pnList) {
//		String[] strArray = new String[pnList.size()];
//		pnList.toArray(strArray);
//		return strArray;
//	}

	public String[] getProductsNames() {
		return productsNames;
	}

	public void setProductsNames(String[] productsNames) {
		this.productsNames = productsNames;
	}

	private Connection getConnection() throws SQLException {
		DataSource ds = DbUtil.getInstance().getDataSource();
		Connection conn = ds.getConnection();
		return conn;
	}

	private ArrayList<String> getNames() throws SQLException {
		ArrayList<String> pnList = new ArrayList<String>();
		Connection conn = getConnection();
		Statement st = conn.createStatement();
		try {
			ResultSet result = st.executeQuery("SELECT nume FROM produse");
			while (result.next()) {
				pnList.add(result.getString("nume"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			st.close();
			conn.close();
		}
		return pnList;
	}
}
